package work.test01waitandnotify1;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

//存入包裹
public class DepositParcel implements Runnable {

    @Override
    public void run() {
        /*
        1、快递员往包裹箱里存入包裹
            如果包裹箱快递已满，就等用户取了快递在存入
            如果包裹箱子没满，则存入快递
        2、存入后修改包裹箱里包裹的数量
        3、唤醒用户取快递
         */
        while (true) {
            //获取锁
            ParcelBox.getLock().lock();
            try {
                if (ParcelBox.getParcelNum()<=100){//如果包裹箱子没满，则存入快递
                    //存入包裹(随机存入5个包裹)
                    int depositNum = (int)(Math.random() * 5 + 1);
                    //存入后修改包裹箱里包裹的数量
                    int end = ParcelBox.getParcelNum() + depositNum;
                    //判断存入后包裹箱是否存满
                    if (end < 100){//没满，则存入
                        ParcelBox.setParcelNum(end);
                        System.out.println(Thread.currentThread().getName() + "存入了" + depositNum + "个包裹，现包裹箱里还剩" +
                                ParcelBox.getParcelNum() + "个包裹");
                    }else {//满了，则存到100，就等用户取了快递在存入
                        int surplus = 100 - ParcelBox.getParcelNum();
                        ParcelBox.setParcelNum(100);
                        System.out.println("包裹箱子只剩下"+surplus+"个位置，存入"+surplus+"个包裹,包裹箱还剩"
                                +ParcelBox.getParcelNum()+"个包裹");
                        System.out.println("包裹箱已满，等待用户取出!!");
                        //等待用户来取快递
                        ParcelBox.getNewDeposit().await();
                    }
                    //唤醒用户来取快递
                    ParcelBox.getNewDeposit().signalAll();
                }
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                //释放锁
                ParcelBox.getLock().unlock();
            }
        }
    }
}
